package com.mindtree.vi.business.javaservice;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.ResourceBundle;

public class SimpleJavaCompilationService implements JavaService {

	public ServiceResponse invokeService(ServiceCommandType serviceType,
			String fileName) {
		ResourceBundle bundle = ResourceBundle.getBundle("compileLocation");
		File parentFile = new File(bundle.getString("compileLocation"));
		if (!parentFile.exists()) {
			boolean created = parentFile.mkdirs();
		}
		File file = new File(parentFile, fileName);
		try {
			file.createNewFile();
			FileOutputStream outputStream = new FileOutputStream(file);
			// write to a file here
			//outputStream.write(request.getSourceCode().getBytes());
			outputStream.flush();
			outputStream.close();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		ServiceResponse xmlResponse = new ServiceResponse();
		InputStream stream = null;
		Process process;
		try {
			process = Runtime.getRuntime().exec(
					serviceType.getType() + parentFile.getPath() + "\\"
							+ fileName);
			if (process.getErrorStream().markSupported()) {
				process.getErrorStream().mark(0);
			}
			int firstChar = process.getErrorStream().read();
			boolean error = firstChar != -1;

			if (!error) {
				stream = process.getInputStream();
			} else {
				stream = process.getErrorStream();
				if (process.getErrorStream().markSupported()) {
					process.getErrorStream().reset();
				}
			}
			StringWriter writer = new StringWriter();
			int data = 0;
			int count = 0;
			while ((data = stream.read()) != -1) {
				count++;
				if (count == 1) {
					writer.write(firstChar);
				}
				writer.write(data);
			}
			System.out.println("count is " + count);
			if (count == 0) {
				xmlResponse.setCode(StatusCode.COMPILE_SUCCESS);
				xmlResponse.setMessage(StatusCode.COMPILE_SUCCESS.name());
			} else {
				xmlResponse.setMessage(writer.getBuffer().toString());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return xmlResponse;

	}

}
